const http = require('http')
const fs = require('fs')
const urlLib = require('url')
const querystring = require('querystring')


let users = {}
let server = http.createServer(function(req,res){
	// res.write('ddddd')
	let str = ''
	req.on('data',function(data){
		str += data
		// const POST = querystring.parse(str)
	})
	req.on('end',function(){
		let obj = urlLib.parse(req.url, true)
		let url = obj.pathname
		const GET = obj.query

		let file_name = './www' + url
		if(url == '/user'){
			switch(GET.act){
				case 'reg':
					if(users[GET.user]){
						res.write('{ok:false,msg:"该用户名被注册"}')
					}else{
						res.write('{ok:true,msg:"注册成功"}')
						users[GET.user] = GET.pass
					}
				break;
				case 'login':
					if(users[GET.user] == null){
						res.write('{ok:false,msg:"用户不存在"}')
					}else if(users[GET.user] != GET.pass){
						res.write('{ok:false,msg:"用户名或者密码错误"}')
					}else{
						res.write('{ok:true,msg:"登录成功"}')
					}
				break;
				default:
					res.write('{ok:false,msg:"未知的act"}')
				break;
			}
			res.end();
		}else{
			fs.readFile(file_name,function(err,data){
				if(err){
					res.write('404')
				}else{
					res.write(data)
				}
				res.end()
			})
		}
		
	})
})

server.listen(8080)